package com.yidu.ladder.system.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yidu.ladder.system.domain.User;
import com.yidu.ladder.system.service.LoginService;
import com.yidu.ladder.util.MD5Util;

@Controller
@RequestMapping("/page/")
public class PageController {
	@Autowired
	private LoginService loginService;
	
	
	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
	
	/**
	 * 后台用户登录的方法 
	 * @param username 用户账号
	 * @param password 密码
	 * @return 页面
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(User user, HttpServletRequest request) {
		// 打印账号和密码
		String md5Password = MD5Util.MD5Encode(user.getPassword(), "UTF-8");
		// 自己写调用根据 用户账号 查询信息的方法
		User userObj = loginService.queryUserPhone(user.getUserPhone());
		//定义一个map集合存储返回前台的数据
		Map<String, Object> map = new HashMap<String, Object>();
		//判断是否存在这个账号
		if (userObj == null) {
			map.put("err", "0"); // 0为账号不存在
			return map;
		} else if (!md5Password.equals(userObj.getPassword())) {// 密码是否正确
			map.put("err", "1"); // 1为密码错误
			return map;
		} else {
			//将用户存储到服务器的session域
			request.getSession().setAttribute("user", userObj);
			map.put("user", userObj);
			map.put("url", "views/index.html"); // 首页请求路径
			return map;
		}
	}
	
	@RequestMapping(value = "getUser", method = RequestMethod.GET)
	@ResponseBody
	public User getUser(HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("user");
		return user;
	}
	
	@RequestMapping(value = "clearUser", method = RequestMethod.GET)
	@ResponseBody
	public void clearUser(HttpServletRequest request){
		request.getSession().removeAttribute("user");
	}
	
}
